/*
 * @Descripttion: 
 * @Author: cuidm
 * @Date: 2022-08-23 17:07:16
 * @LastEditors: cuidm
 * @LastEditTime: 2022-08-24 16:20:30
 * 转移主机到空闲机池
 */
import React, { useState, useEffect, useRef } from "react";
import { Form, Button, Input, Affix, Select, message, Space, Switch, Drawer, Row, Col, Modal, Tree, Spin, Empty, Radio, Alert } from "antd";
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { useModelAssociateType } from "@/components";
import cmdbres from "@/data/cmdbres";
import hcpiam from "@/data/hcpiam";
import request, {requestIAM} from '@/utils/request';
import regexpUtil from "@/utils/regexpUtil";
import hcpUtils from "@/utils/hcpUtils";
import "../index.less";

const user = hcpUtils.getUser();
const IdleMachineModule = ({ bizInfo, serviceInfo, rowKeys, visible, setVisible, onFinish, cmModuleId}) => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [treeData, setTreeData] = useState([]);
    const [dataLoading, setDataLoading] = useState(true);
    const [selectTreeNode, setSelectTreeNode] = useState();
    
    const iconName = (code, instanceName) => {
        let name = { biz: "业", set: "集", service: "模" }[code];
        let f = instanceName?.substring(0,1)??'层';
        return  name ? name : f
    }
    //空闲机池
    const dealPools = (pools) => {
        let obj = Object({
            key: pools.setId,
            title: pools.setName,
            icon: <span className="icon">{iconName('', pools.setName)}</span>,
            children: [],
            moduleCode: pools.moduleCode
        },pools);

        if(pools.serviceInstances) {
            pools.serviceInstances.map(item=> {
                obj.children.push({
                    key: item.serviceId,
                    title: <>
                        <span>{item.serviceName}</span>
                        <Radio 
                            className="btn"
                            onClick={()=>setSelectTreeNode(item)} 
                            value={item.serviceId}
                        />
                    </>,
                    icon: <span className="icon">{iconName('', item.serviceName)}</span>,
                    ...item
                })
            })
            delete obj.serviceInstances;
        }
        return [obj];
    }

    const queryBizPool = async () => {
        try {
            const res = await request({
                ...cmdbres.queryBizPool(bizInfo.bizId),
                params: {},
            });
            if(res && res.data) {
                const arr = [{
                    ...bizInfo,
                    key: bizInfo.bizId,
                    title: bizInfo.bizName,
                    children: dealPools(res.data)
                }]
                setTreeData(arr);
            }
            setDataLoading(false);
        } catch (error) {
            console.log(error);
        } 
    };

    useEffect(() => {
        if(visible && bizInfo) {
            console.log('serviceInfo', serviceInfo);
            queryBizPool();
        }
    }, [visible, bizInfo]);

    const onSubmit = async () => {
        const removeObj = [];
        serviceInfo?.map(info=> {
            info.serviceInstances.map(item=> {
                removeObj.push({
                    serviceInstanceId: item.serviceId,//模块ID
                    serverId: info.server?.cm_unid,//主机ID
                })
            })
        });
        setLoading(true);
		let res = await request({
			...cmdbres.moveToService,
			data: {
                author: user.staffName,
                bizId: bizInfo.bizId,
                cmModuleId,
                serverIds: rowKeys,
                addToServices: [selectTreeNode.serviceId],
                serviceInstanceOptions: removeObj
            }
		});
		setLoading(false);
		if (res && res.code == 200) {
			setVisible(false);
			message.success(`转移主机到空闲机池成功！`);
			if (typeof onFinish == "function") onFinish(res);
		}
	};

    const onCancel = () => {
        setVisible(false);
    }

    const onClear = () => {
        setSelectTreeNode();
    }

    return (
        <Modal
            className="hcp-tip-modal hcp-modal-md"
            title="转移主机到空闲机池"
            visible={visible}
            onCancel={onCancel}
            footer={null}
            destroyOnClose
            maskClosable={false}
            afterClose={() => {
                form.resetFields();
                setSelectTreeNode();
            }}
        >
            <Form
                form={form}
                labelCol={{ span: 5}}
                wrapperCol={{ span: 17 }}
                name="basic"
                onFinish={onSubmit}
            >
                <Row className="box-content">
                    <Col span={12} className="topo-content">
                        <h3 className="title">拓扑列表</h3>
                        {
                            dataLoading ? <Spin /> :
                            treeData.length ?
                            <Radio.Group value={selectTreeNode?.serviceId} style={{width: '100%'}}>
                                <Tree
                                    className="resource-topo-tree"
                                    showIcon
                                    defaultExpandAll
                                    defaultExpandParent
                                    treeData={treeData}
                                    onSelect={(selectedKeys, e) => {
                                        const node = e.node;
                                        if(node.moduleCode == "service") {//只能选择模块
                                            setSelectTreeNode(node);
                                        }
                                    }}
                                    loading={loading}
                                />
                            </Radio.Group>
                            :<Empty
                                style={{
                                    border: 'rgb(215,215,215) solid 1px',
                                    width: 500,
                                    padding: '100px 0',
                                }}
                                image={Empty.PRESENTED_IMAGE_SIMPLE}
                            />
                        }
                        
                    </Col>
                    <Col span={12} className="preview-content">
                        <h3 className="title">结果预览</h3>
                        <div className="desc">
                            <span>已选择【<span className="num">{selectTreeNode? 1 : 0}</span>】个模块 </span>
                            <span type="primary" onClick={onClear}>清空</span>
                        </div>
                        { selectTreeNode && 
                        <Alert 
                            showIcon
                            closable
                            type="info"
                            icon={<span className="icon">{iconName('', selectTreeNode.serviceName)}</span>} 
                            message={selectTreeNode.serviceName} 
                            onClose={onClear}
                        /> }
                    </Col>
                </Row>
                
                <div className="hcp-modal-body-footer" style={{marginTop: 20}}>
                    <Form.Item wrapperCol={{ span: 24 }}>
                        <Button onClick={onCancel} >
                            取消
                        </Button>
                        <Button type="primary" htmlType="submit" loading={loading} disabled={!(selectTreeNode && selectTreeNode.serviceId)}>
                            提交
                        </Button>
                    </Form.Item>
                </div>
            </Form>
        </Modal>
    );
};

export default IdleMachineModule;